<template>
	<main :style="{ backgroundImage: `url(${url})` }">
		<template v-if="currentWordItem">
            <div class="header" >
				<div class="left">
					<img alt="" class="back" :src="url1" @click="goBack" />
					<span>{{ name }}</span>
				</div>
				<div class="middle">
					<span :style="{ color: titleColor() }">单词练习</span>
				</div>
				<div class="right">
					<Progress class="progress" :max="totalWords" :value="currentWordIndex + 1" :progressColor="progressColor()"></Progress>
					<!-- <div class="progress-wrap" v-if="totalWords">
						<progress :class="[`progress-${path}`]" :max="totalWords" :value="currentWordIndex + 1"></progress>
						<span>{{ `${currentWordIndex + 1}/${totalWords}` }}</span>
					</div> -->
				</div>
			</div>
            <div class="article">
				<div v-aspectRatio class="keyboard-box" :style="{ backgroundColor: cardWrapColor() }">
					<template v-if="currentWordItem.type == 3">
						<div class="boder-box1">
							<span class="isWordVisible" :class="{ 'isWordVisible-cn': currentWordItem.type == 1}" v-if="show" v-html="currentWord"></span>
							<span class="isText" v-html="displayText" v-else></span>
							<div class="img-box">
								<img :src="urlCPlay" alt="" class="img" @click="playAudio" />
							</div>
						</div>
					</template>
					<template v-else>
						<div class="boder-box">
							<div class="img-box1">
								<img :src="urlCPlay" alt="" class="img" @click="playAudio" />
							</div>
							<span class="isWordVisible" :class="{ 'isWordVisible-cn': currentWordItem.type == 1}" v-if="show" v-html="currentWord"></span>
							<span class="isText" v-html="displayText" v-else></span>
						</div>
					</template>
					<div class="letter-box">
						<div
							class="letter-btn"
							:class="{
								[gradeType === 'primary' ? 'letter' : 'letters']: true,
								[gradeType === 'primary' ? 'answer' : 'answers']: selectedWord === item.title && isCorrect,
								error: selectedWord === item.title && !isCorrect,
								disabled: letterDisabled,
							}"
							v-for="(item, index) in displayedWords"
							:key="index"
							v-html="item.content"
							@click="checkWord(item.title)">
						</div>
					</div>
				</div>
			</div>
			<div class="footer">
				<div class="footer-wrap">
					<div @click.prevent="prevWord"
						class="footer-btn-wrap footer-btn-left-wrap">
						<div class="footer-btn">
							<template v-if="currentWordIndex == 0">
								<img alt="" :src="urlPreGray" style="width: 100%; height: 100%" />
							</template>
							<template v-else>
								<img alt="" :src="urlPre" style="width: 100%; height: 100%" />
							</template>
						</div>
						<span class="footer-btn-title">上一个</span>
					</div>

					<div @click.prevent="nextWord"
						class="footer-btn-wrap  footer-btn-right-wrap">
						<div class="footer-btn">
							<!-- <template v-if="currentWordIndex >= totalWords - 1">
								<img alt="" :src="urlNextGray" style="width: 100%; height: 100%" />
							</template>
							<template v-else>
								<img alt="" :src="urlNext" style="width: 100%; height: 100%" />
							</template>	 -->
							<img alt="" :src="urlNext" style="width: 100%; height: 100%" />					
						</div>
						<span class="footer-btn-title">{{ currentWordIndex >= totalWords - 1 ? '提交': '下一个' }}</span>
					</div>
				</div>
			</div>
		</template>
		<Dialog :open="recordingOpen">
			<div class="dialog-wrap-finished">
				<div class="content">
					<img alt="" src="../public/assets/vocabulary/ty_tb_14_pt@2x.png" />
					<span>你真棒，完成了全部的单词学习。</span>
					<div class="control">
						<button @click="goBack" class="button btn-back"
							:style="{ background: buttonBackColor() }">返回单元</button>
						<button @click="restartGame" class="button btn-agin"
							:style="{ background: buttonAginColor() }">再来一遍</button>
					</div>
				</div>
			</div>
		</Dialog>
	</main>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import Dialog from "../component/dialog/index.vue";
import { getPracticeinterface } from "../api/expression.js";
import Grade from "../utils/grade.js"
import '../css/evaluation.css'
import Progress from "../component/progress/index.vue";

const router = useRouter(); // 获取路由实例
const route = useRoute();
const { id, name } = route.query;

const path = window.gradeId > 61 ? 'middle' : 'primary';
const gradeType = window.gradeId > 61 ? 'middle' : 'primary';

const url = new URL(`../public/assets/vocabulary/${path}/d_bg.png`, import.meta.url).href;
const url1 = new URL(`../public/assets/book/${path}/back.png`, import.meta.url).href;
const urlNext = new URL(`../public/assets/expression/${path}/next.png`, import.meta.url).href;
const urlNextGray = new URL(`../public/assets/expression/${path}/next_gray.png`, import.meta.url).href;
const urlPre = new URL(`../public/assets/expression/${path}/pre.png`, import.meta.url).href;
const urlPreGray = new URL(`../public/assets/expression/${path}/pre_gray.png`, import.meta.url).href;
const urlPrompt = new URL(`../public/assets/expression/${path}/prompt.png`, import.meta.url).href;
const urlCPlay = new URL(`../public/assets/expression/${path}/c_play.png`, import.meta.url).href;


// 引入音频文件
const errorSound = new Audio("assets/audio/prompt/error.wav");
const completeMusic = new Audio("assets/audio/prompt/jiesuan.mp3"); // 完成音乐
const recordingOpen = ref(false);
const words = ref([]); // 将 words 定义为 ref，以便可以动态更新
const totalWords = ref(0); // 总单词数量
const currentWordIndex = ref(0); // 当前单词索引
const currentWord = ref(""); // 当前单词
const completedWords = ref(1); // 初始值设为1，表示已完成的单词数量
const currentWordItem = ref(null) // 当前的word数据
const selectedWord = ref(""); // 用户选择的单词
const isCorrect = ref(false); // 是否选择正确

const backgroundDiv = ref(null); // 使用 ref 来引用背景元素
const displayText = ref();
const previousErrors = ref([]); // 存储之前错误的单词

const letterDisabled = ref(false)

function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
}


// 函数用于获取当前样式
function getCurrentStyles() {
	// if (window.matchMedia("(max-width: 600px)").matches) {
	// 	return {
	// 		color: "#f1973b",
	// 		fontSize: "36px", // 小屏幕字体大小
	// 		marginBottom: "30px", // 小屏幕下边距
	// 	};
	// } else if (window.matchMedia("(min-width: 601px) and (max-width: 900px)").matches) {
	// 	return {
	// 		color: "#f1973b",
	// 		fontSize: "42px", // 中等屏幕字体大小
	// 		marginBottom: "40px", // 中等屏幕下边距
	// 	};
	// } else {
	// 	return {
	// 		color: "#f1973b",
	// 		fontSize: "38px",
	// 		marginBottom: "50px",
	// 	};
	// }
	if (path == 'middle') {
		return '#4392F4'
	} else {
		return '#f1973b'
	}

}

function updateBackground() {
	if (backgroundDiv.value) {
		// 确保元素存在
		if (gradeType === "primary") {
			backgroundDiv.value.style.backgroundImage = "url('../public/assets/beijing.png')"; // 当变量为1时的背景图
		} else {
			backgroundDiv.value.style.backgroundImage = "url('../public/assets/middleschool.png')"; // 当变量不为1时的背景图
		}
	}
}

const show = ref(true);
let currentAudio = new Audio(); // 当前播放的音频对象

const displayedWords = computed(() => {
	const randomWords = [...words.value]; // 复制原始单词数组
	if (randomWords.length === 0) return []; // 如果没有单词，返回空数组
	// const current = randomWords.splice(currentWordIndex.value, 1)[0]; // 获取当前单词并从数组中移除

	const current = randomWords[currentWordIndex.value];
	const filterWords = randomWords.filter((word) => {
		return word.content !== current.content;
	});
	let randomIndex = Math.floor(Math.random() * filterWords.length);

	const randomSelection = [current, filterWords[randomIndex]]; // 初始化选择数组，包含当前单词

	// // 过滤掉之前错误的单词
	// const filteredWords = randomWords.filter(word => !previousErrors.value.includes(word.title));

	// // 随机选择一个其他单词，确保不在之前错误的单词中
	// while (randomSelection.length < 2 && filteredWords.length > 0) {
	// 	const randomIndex = Math.floor(Math.random() * filteredWords.length);
	// 	randomSelection.push(filteredWords[randomIndex]);
	// 	filteredWords.splice(randomIndex, 1); // 从过滤后的数组中移除已选择的单词
	// }

	// 随机打乱选择的单词顺序
	return randomSelection.sort(() => Math.random() - 0.5); // 返回随机顺序的单词
});

const playAudio = () => {
	// if (currentAudio) {
	// 	currentAudio.pause(); // 停止当前音频
	// }
	if (words.value[currentWordIndex.value]) {
		// 确保当前单词存在
		const audioUrl = words.value[currentWordIndex.value].url; // 获取当前单词对应的音频 URL
		if (audioUrl) {
			if (!currentAudio.paused) {
				currentAudio.pause();
			}
			currentAudio.src = audioUrl;
			currentAudio.play();
			// currentAudio = new Audio(audioUrl); // 创建 Audio 对象
			// currentAudio.play().catch(error => {
			// 	console.error("音频播放失败:", error); // 捕获播放错误
			// });
		}
	}
};

let correctTimer = null;
let completeTimer = null;
const checkWord = word => {
	if (letterDisabled.value) {
		return;
	}
	if (!words.value[currentWordIndex.value]) return; // 确保当前单词存在
	const correctWord = words.value[currentWordIndex.value].type === 3 ? words.value[currentWordIndex.value].title : currentWord.value; // 获取正确的单词

	selectedWord.value = word; // 记录用户选择的单词

	isCorrect.value = word === correctWord; // 检查是否正确
	if (isCorrect.value) {
		if (completedWords.value < totalWords.value) {
			completedWords.value++; // 增加已完成的单词数量
		}
		const currentWordObj = words.value[currentWordIndex.value];
		const currentStyles = getCurrentStyles(); // 获取当前样式
		if (currentWordObj.type === 3) {
			if (currentWordObj.sentence.includes("_")) {
				// const replacement = `<span style="color:${currentStyles.color}; font-size:${currentStyles.fontSize}; margin-bottom:${currentStyles.marginBottom}; display: inline-block;">${currentWordObj.content}</span>`;
				const replacement = `<span style="color:${currentStyles};">${currentWordObj.content}</span>`;
				displayText.value = currentWordObj.sentence.replace("______", replacement);
				show.value = false;
			} else {
				displayText.value = `${currentWordObj.sentence} <span style="color:${currentStyles};">${currentWordObj.content}</span>`;
			}
		} else {
			show.value = true;
		}
		
		currentAudio.pause(); // 停止当前音频
		completeMusic.play(); // 播放完成音乐
		letterDisabled.value = true;
		if (correctTimer) {
			clearTimeout(correctTimer);
			correctTimer = null;
		}
		// 仅在完成所有单词后弹出弹框
		// if (currentWordIndex.value === totalWords.value - 1) {
		// 	completeTimer = setTimeout(() => {
		// 		recordingOpen.value = true; // 延迟3秒后弹出弹框
		// 		currentAudio.pause(); // 停止当前音频
		// 		letterDisabled.value = false;
		// 	}, 2000);
		// } else {
		// 	completeTimer = setTimeout(resetGame, 2000); // 1秒后重置
		// }
		completeTimer = setTimeout(resetGame, 2000); // 1秒后重置
	} else {
		// 播放错误音频
		errorSound.currentTime = 0; // 重置音频播放时间
		errorSound.play(); // 播放错误音频
		if (correctTimer) {
			clearTimeout(correctTimer);
			correctTimer = null;
		}
		correctTimer = setTimeout(() => {
			selectedWord.value = ""; // 清空用户选择的单词
			isCorrect.value = false; // 重置正确状态
		}, 2000);
	}
};

const resetGame = () => {

	if (currentWordIndex.value >= totalWords.value - 1) {
		recordingOpen.value = true; // 延迟1秒后弹出弹框
		return;
	}

	letterDisabled.value = false;
	show.value = true;
	selectedWord.value = ""; // 清空用户选择的单词
	isCorrect.value = false; // 重置正确状态
	// currentWordIndex.value = (currentWordIndex.value + 1) % totalWords.value; // 移动到下一个单词

	currentWordIndex.value++; // 移动到下一个单词
	currentWord.value = words.value[currentWordIndex.value] ? (words.value[currentWordIndex.value].type === 3 ? words.value[currentWordIndex.value].sentence : words.value[currentWordIndex.value].title) : ""; // 获取新的单词
	currentWordItem.value = words.value[currentWordIndex.value];
	playAudio(); // 播放新单词的音频

	// // 更新当前单词索引
	// if (currentWordIndex.value < totalWords.value - 1) {
	// 	currentWordIndex.value++; // 移动到下一个单词
	// 	currentWord.value = words.value[currentWordIndex.value] ? (words.value[currentWordIndex.value].type === 3 ? words.value[currentWordIndex.value].sentence : words.value[currentWordIndex.value].title) : ""; // 获取新的单词
	// 	currentWordItem.value = words.value[currentWordIndex.value];
	// 	playAudio(); // 播放新单词的音频
	// } else {
	// 	currentWordIndex.value = totalWords.value - 1; // 如果到达最后一个单词，则保持在最后一个
	// 	currentWord.value = words.value[currentWordIndex.value] ? (words.value[currentWordIndex.value].type === 3 ? words.value[currentWordIndex.value].sentence : words.value[currentWordIndex.value].title) : ""; // 获取新的单词
	// 	currentWordItem.value = words.value[currentWordIndex.value];
	// }

};

const goBack = () => {
	router.go(-1);
	currentAudio.pause(); // 停止当前音频
	recordingOpen.value = false;
};

const restartGame = () => {

	letterDisabled.value = false;
	show.value = true;
	selectedWord.value = ""; // 清空用户选择的单词
	isCorrect.value = false; // 重置正确状态

	completedWords.value = 1; // 重置已完成的单词数量为1
	currentWordIndex.value = 0; // 重置为第一个单词
	currentWord.value = words.value[currentWordIndex.value] ? (words.value[currentWordIndex.value].type === 3 ? words.value[currentWordIndex.value].sentence : words.value[currentWordIndex.value].title) : ""; // 获取新的单词
	playAudio(); // 播放第一个单词的音频
	recordingOpen.value = false;
};

const progressWidth = computed(() => {
	return `${(completedWords.value / totalWords.value) * 100}%`; // 计算进度条宽度
});

// 控制上一个按钮的可用状态
const isPrevDisabled = computed(() => currentWordIndex.value === 0);

// 控制下一个按钮的可用状态
const isNextDisabled = computed(() => currentWordIndex.value === totalWords.value - 1);

const getPracticeDetail = async () => {
	try {
		const res = await getPracticeinterface(id); // 确保使用正确的 API 函数
		console.log("res", res);
		if (res.data && res.data.length) {
			words.value = shuffleArray(res.data); // 动态赋值
			totalWords.value = words.value.length; // 更新总单词数量
			currentWordIndex.value = 0; // 重置当前单词索引
			currentWordItem.value = words.value[0];
			currentWord.value = words.value[currentWordIndex.value] ? (words.value[currentWordIndex.value].type === 3 ? words.value[currentWordIndex.value].sentence : words.value[currentWordIndex.value].title) : ""; // 获取新的单词
			playAudio(); // 播放第一个单词的音频
		}
	} catch (error) {
		console.error(error); // 打印错误信息
	}
};

// 在组件挂载时初始化
onMounted(() => {
	// updateBackground(); // 在 mounted 时更新背景
	getPracticeDetail(); // 获取单词数据
});

onUnmounted(() => {
	if (completeTimer) {
		clearTimeout(completeTimer);
		completeTimer = null;
	}
	if (correctTimer) {
		clearTimeout(correctTimer);
		correctTimer = null;
	}
});

// 其他函数保持不变...
const prevWord = () => {
	if (currentWordIndex.value <= 0) {
		return;
	}
	if (completeTimer) {
		clearTimeout(completeTimer);
		completeTimer = null;
	}
	// if (currentWordIndex.value > 0) {
	letterDisabled.value = false;
	show.value = true;
	selectedWord.value = ""; // 清空用户选择的单词
	isCorrect.value = false; // 重置正确状态

	currentWordIndex.value--; // 移动到上一个单词
	currentWordItem.value = words.value[currentWordIndex.value];

	currentWord.value = words.value[currentWordIndex.value] ? (words.value[currentWordIndex.value].type === 3 ? words.value[currentWordIndex.value].sentence : words.value[currentWordIndex.value].title) : ""; // 更新当前单词
	completedWords.value--; // 减少已完成的单词数量
	playAudio(); // 播放上一个单词的音频
	// }
};

const nextWord = () => {
	if (currentWordIndex.value >= totalWords.value - 1) {
		currentAudio.pause(); // 停止当前音频
		completeMusic.pause();
		errorSound.pause();
		recordingOpen.value = true; // 延迟1秒后弹出弹框
		return;
	}
	if (completeTimer) {
		clearTimeout(completeTimer);
		completeTimer = null;
	}
	letterDisabled.value = false;
	show.value = true;
	selectedWord.value = ""; // 清空用户选择的单词
	isCorrect.value = false; // 重置正确状态
	// if (currentWordIndex.value < totalWords.value - 1) {
	currentWordIndex.value++; // 移动到下一个单词
	completedWords.value++; // 增加已完成的单词数量
	// }
	currentWordItem.value = words.value[currentWordIndex.value];
	currentWord.value = words.value[currentWordIndex.value] ? (words.value[currentWordIndex.value].type === 3 ? words.value[currentWordIndex.value].sentence : words.value[currentWordIndex.value].title) : ""; // 更新当前单词
	playAudio(); // 播放当前单词的音频
};

// 监听窗口大小变化
window.addEventListener("resize", () => {
	const updatedStyles = getCurrentStyles(); // 更新样式
	// 这里可以根据需要更新 displayText.value
});

const titleColor = () => {
	if (path == 'middle') {
		return '#222'
	} else {
		return '#854B22'
	}
}
const buttonBackColor = () => {
    if (path == 'middle') {
        return '#FFA53E'
    } else {
        return 'linear-gradient(to bottom, #FFC55E, #ED9900)'
    }
}

const buttonAginColor = () => {
    if (path == 'middle') {
        return '#1E4BA6'
    } else {
        return 'linear-gradient(to bottom, #85D389, #61BD66)'
    }
}

const progressColor = () => {
    if (path == 'middle') {
        return '#1E4BA6'
    } else {
        return '#FFB530'
    }
}

const cardWrapColor = () => {
    if (path == 'middle') {
        return '#fff'
    } else {
        return '#FFFAF1'
    }
}

</script>

<style scoped>

.keyboard-box {
	background-color: #FFFAF1;
	border-radius: 1rem;
	width: 70%;
	/* height: 100%; */
	box-sizing: border-box;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: space-between;
	position: relative;
	padding: 0 2% 4% 2%;
    /* margin: 2rem 0 1.3rem 0; */

}
.boder-box {
	/* width: 653px; */
	/* height: 40%; */
	/* margin-top: 51px; */
	/* display: flex;
	flex-direction: column;
	align-items: center; */
	flex: 1;
	/* justify-content: center; */
	font-size: 2.2rem;
	color: #222222;
	margin: 1rem 2rem;
	font-family: 'text-cn';
}

.boder-box1 {
	/* width: 653px; */
	/* height: 40%; */
	/* margin-top: 51px; */
	display: flex;
	flex-direction: column;
	align-items: center;
	flex: 1;
	justify-content: center;
	font-size: 2.2rem;
	color: #222222;
	margin: 1rem 2rem;
	font-family: 'text-cn';
}

.img-box {
	display: flex;
	flex-direction: column;
	justify-content: space-between;
	position: absolute;
	right: 2%;
	top: 4%;
	/* height: 5rem; */
}

.img-box .img {
	cursor: pointer;
	width: 2rem;
	float: right;
	/* margin-top: 2rem; */
}
.img-box1 {
	/* margin: 20% 0 10% 0; */
	/* flex: 1; */
	/* margin-top: 10rem; */
	height: 50%;
	/* margin: 4rem 0 4rem 0; */
	/* display: flex;
	justify-content: center;
	align-items: center; */
	position: relative;
}
.img-box1 .img {
	cursor: pointer;
	width: 3rem;
	position: absolute;
	top: 70%;
	left: 50%;
	transform: translate(-50%,-50%);
	/* margin: 0 auto; */
	/* margin-top: 2rem; */
}


.letter-box {
	display: flex;
	justify-content: space-around;
	align-items: center;
	flex-wrap: wrap;
	width: 100%;
	/* width: 90%; */
}
/* word-wrap:break-word;  */
.letter-btn {
	word-wrap:break-word;
	box-sizing: border-box;
	width: 48%; /* 增加宽度以适应单词 */
	/* height: 3rem; */
	/* min-height: 4.6rem; */
	height: 100%;
	padding: 0.5rem;
	cursor: pointer; /* 设置鼠标光标为小手图标 */
	border-radius: 0.5rem;
	font-size: 1.8rem;
	text-align: center;
	font-family: 'text-en';
	
}
.letter {
	background-color: #fff1d7;
	/* display: flex;
	align-items: center;
	justify-content: center; */

	/* margin-right: 38px;
	margin-bottom: 10px; */
	color: #ffb530;
}
.letters {
	background-color: #edf2ff;
	color: #4392f4;
}
.error {
	background-color: #ff7866;
	color: #fff;
}

.disabled {
	background-color: #F4F4F4;
	color: #999;
}

.answer {
	background-color: #78ba6f;
	color: #fff;
}

.answers {
	background-color: #4392f4;
	color: #ffffff;
}
.isWordVisible {
	/* font-size: 38px; */
	/* color: #000000; */
	/* margin-bottom: 50px; */
	font-family: 'text-en';
	/* flex: 1; */
}
.isText {
	font-family: 'text-en';
}
.isWordVisible-cn {
	font-family: 'text-cn';
}
</style>

